package com.houor.device.controller.handler;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class MessageHandler extends SimpleChannelInboundHandler<Object> {

	private static Logger logger = LoggerFactory.getLogger(MessageHandler.class);

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf) msg;
		byte[] req = new byte[in.readableBytes()];
		in.readBytes(req);

		InetSocketAddress sa = (InetSocketAddress) ctx.pipeline().channel().remoteAddress();
		System.out.println(sa.getAddress());

		for (int i = 0; i < req.length; i++) {
			String temp = Integer.toHexString(req[i]);
			logger.debug((temp.length() > 2 ? temp.substring(6) : temp) + " ");
		}

		ByteBuf out = ctx.alloc().buffer(req.length);

		out.writeBytes(req);

		ctx.writeAndFlush(out);

	}
}
